package com.dragee.modules.work.controller;

import cn.hutool.core.util.StrUtil;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.common.VerifyParam;
import com.dragee.modules.work.entity.OrderEntity;
import com.dragee.modules.work.entity.ShopCustomerEntity;
import com.dragee.modules.work.entity.ShopProjectEntity;
import com.dragee.modules.work.po.OrderStatus;
import com.dragee.modules.work.service.*;
import com.dragee.modules.work.vo.PlaceOrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;



/**
 * 订单表
 *
 * @author tc
 * @email tc@mail.com
 * @date 2023-06-16 15:08:48
 */
@RestController
@RequestMapping("work/order")
@Api(tags = "订单表")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopProjectService shopProjectService;
    @Autowired
    private ShopProjectGoodsService shopProjectGoodsService;
    @Autowired
    private ShopCustomerService shopCustomerService;
    @Autowired
    private ShopGoodsService shopGoodsService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private OrderGroupService orderGroupService;

    /**
     * 列表
     */
    @GetMapping("list")
    @ApiOperation("订单表列表")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderService.queryPage(params);
        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @GetMapping("{id}")
    @ApiOperation("订单表信息")
    public R info(@PathVariable("id") Long id){
		OrderEntity order = orderService.getById(id);
        return R.ok().put("data", order);
    }


    /**
     * 保存
     */
    @PostMapping("placeOrder")
    @ApiOperation("用户下单")
    public R placeOrder(@RequestBody PlaceOrderVo vo) {
        VerifyParam.notNull(vo);
        ShopProjectEntity project = shopService.getProjectById(vo.getProjectId());
        OrderEntity order = new OrderEntity();
        order.setSourceType(StrUtil.isBlank(vo.getSourceType()) ? "wx" : vo.getSourceType());
        order.setAppointTime(vo.getAppoindTime());
        order.setPlaceOrderType(vo.getPlaceOrderType());
        order.setProjectId(vo.getProjectId());
        order.setManHourCost(project.getManHourCost());
        order.setProjectName(project.getName());
        order.setShopId(project.getShopId());
        order.setPrice(project.getPrice());
        order.setDiscountPrice(project.getPrice());
        if (StrUtil.isNotBlank(order.getManHourCost())) {
            order.setNeedPay(new BigDecimal(project.getPrice())
                    .add(new BigDecimal(order.getManHourCost())).toString());
        } else {
            order.setNeedPay(project.getPrice());
        }
        order.setClerkId(vo.getClerkId());
        if ("wx".equals(order.getSourceType())) {
            if ("拼团".equals(order.getPlaceOrderType())) {
                order.setStatus(OrderStatus.grouping.getValue());
            } else {
                order.setStatus(OrderStatus.waitShopConfirm.getValue());
            }
        } else {
            order.setStatus(OrderStatus.finishOrder.getValue());
        }
        order.setCustomer(vo.getCustomer());
        order.setCustomerTel(vo.getCustomerTel());
        orderService.saveOrUpdate(order);
        // 如果是拼团 设置拼团信息
        if ("拼团".equals(order.getPlaceOrderType())) {
            orderGroupService.setOrderGrouping(order, vo.getGroupId());
        }
        // 保存用户信息
        ShopCustomerEntity customer = shopCustomerService.getCustomerByTel(order.getShopId(), vo.getCustomerTel());
        if (customer == null) {
            customer = new  ShopCustomerEntity();
        }
        customer.setShopId(project.getShopId());
        customer.setName(vo.getCustomer());
        customer.setTel(vo.getCustomerTel());
        customer.setClerkId(order.getClerkId());
        shopCustomerService.saveOrUpdate(customer);
        if (order.getStatus().equals(OrderStatus.finishOrder.getValue())) {
            orderService.settlePoints(order);
        }
        return R.ok();
    }

    @GetMapping("confirmOrder")
    @ApiOperation("店家确认订单")
    public R confirmOrder(@RequestParam("orderId") String orderId,
                          @RequestParam("result") String result){
        OrderEntity order = orderService.getById(orderId);
        if ("yes".equals(result)) {
            order.setStatus(OrderStatus.appointSuccess.getValue());
            order.setConfirmTime(new Date());
        } else {
            order.setStatus(OrderStatus.finishCancel.getValue());
        }
        orderService.saveOrUpdate(order);
        return R.ok();
    }

    @GetMapping("finishOrder")
    @ApiOperation("店家完成订单")
    public R finishOrder(@RequestParam("orderId") String orderId, @RequestParam("clerkId") String clerkId){
        // 修改状态
        OrderEntity order = orderService.getById(orderId);
        order.setStatus(OrderStatus.finishOrder.getValue());
        order.setClerkId(clerkId);
        // 库存处理
        BigDecimal cost = shopProjectService.reduceShopGoodsByProject(order.getProjectId());
        order.setGoodsCost(cost.setScale(2, RoundingMode.HALF_UP).toString());
        orderService.saveOrUpdate(order);
        ShopCustomerEntity customer = shopCustomerService.getCustomerByOrderId(order.getId().toString());
        customer.setClerkId(clerkId);
        shopCustomerService.saveOrUpdate(customer);
        orderService.settlePoints(order);
        return R.ok();
    }




    /**
     * 删除
     */
    @GetMapping("delete-by-id")
    @ApiOperation("订单表删除")
    public R delete( String id){
		orderService.removeById(Long.parseLong(id));
        return R.ok();
    }

    @GetMapping("delete-by-ids")
    @ApiOperation("订单表批量删除")
    public R deletes(String ids){
        String[] idArr = ids.split(",");
        Arrays.stream(idArr).forEach(id -> orderService.removeById(Long.parseLong(id)));
        return R.ok();
    }



}
